﻿using AutoMapper;
using PagedList;
using SIG.DAL.Dapper.Model;
using SIG.DAL.Dapper.Repositories;
using SIG.Infrastructure.Configs;

using SIG.ViewModel.Front.Blogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace SIG.WebMVC.Controllers
{
    public class PostsController : BaseController
    {
        private readonly PostRepository _postService;
        private readonly PageMetaRepository _pageMetaService;
        private readonly PostCategoryRepository _postCategoryService;
        private IMapper _mapper;
        public PostsController(IMapper mapper)
        {
            _postService = new PostRepository();
            _postCategoryService = new PostCategoryRepository();
            _pageMetaService = new PageMetaRepository();
            _mapper = mapper;
        }
        // GET: Posts
        public int PageSize = 16;

        public ActionResult Index(int? page, int? categoryId, string keyword)
        {

            var vm = new PostListVM();

            vm.CategoryId = categoryId??0;

            vm.Keyword = keyword;
            vm.PageIndex = (page ?? 1);
            vm.PageSize = SettingsManager.Blog.FrontPageSize;
            int totalCount;
            var postList = _postService.GetListPagedAcitveItems(vm.PageIndex, vm.PageSize, vm.CategoryId.Value, vm.Keyword, out totalCount);
           // var postVMList = _mapper.Map<List<Post>, List<PostVM>>(postList);
            vm.TotalCount = totalCount;

            vm.Posts = new StaticPagedList<Post>(postList, vm.PageIndex + 1, vm.PageSize, vm.TotalCount);

            var categoryList = _postCategoryService.GetActiveItems().OrderByDescending(c => c.Importance).ToList();
            foreach(var item in vm.Posts)
            {
                item.PostCategory = categoryList.FirstOrDefault(m => m.Id == item.CategoryId);
            }


            return View(vm);


        }


        public ActionResult BlogList()
        {
            var lBlogs = _postCategoryService.GetActiveItems().ToList();
            return PartialView("_BlogList", lBlogs);
        }
     
        public ActionResult RecommendPosts()
        {       
            var posts = _postService.GetListPagedRecommendPosts(1,8).ToList();
            return PartialView("_RecommendPosts", posts);
        }

        public ActionResult Detail(int id)
        {
        
            var vPost = _postService.GetById(id);
            if (vPost == null)
                return HttpNotFound();

            vPost.ViewCount += 1;
            _postService.Update(vPost);

            var vm = _mapper.Map<PostDetailVM>(vPost);

            var meta = _pageMetaService.GetPageMeta(ModelType.BLOG, id.ToString());
            if (meta != null)
            {
                vm.Keyword = meta.Keyword;
                vm.Description = meta.Description;
            }         
      
            return View(vm);
        }
    }
}